package com.xiaoc.bulldozer.controller;

import com.xc.framework.common.page.PageDto;
import com.xc.framework.common.utils.BeanUtil;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.BannerDto;
import com.xiaoc.bulldozer.common.dto.BannerQueryDto;
import com.xiaoc.bulldozer.common.model.Banner;
import com.xiaoc.bulldozer.common.service.BannerService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/banner")
public class BannerController extends AdminBaseController {

    public static final Logger logger = LoggerFactory.getLogger(BannerController.class);

    @Resource(name = "bannerService")
    private BannerService bannerService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(BannerQueryDto queryDto) {

        if(queryDto.getPage() == null) queryDto.setPage(1);
        queryDto.setTitle(StringUtils.trimToNull(queryDto.getTitle()));
        
        int count = bannerService.getBannerCountByCondition(queryDto);
        
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pageDto", new PageDto(queryDto.getPage(), count, PageDto.PAGE_SIZE));

        if (count == 0) {
            params.put("queryDto", queryDto);
            return renderHtml("banner/list.html", params);
        }
        
        List<Banner> bannerList = bannerService.getBannerListByCondition(queryDto);
        params.put("bannerList", bannerList);
        params.put("queryDto", queryDto);
        return renderHtml("banner/list.html", params);
    }

    
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public ModelAndView detail(Integer id) {
        Banner banner = null;
        if(id != null) {
            banner = bannerService.getBannerById(id);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("banner", banner);
        return renderHtml("banner/edit.html", params);
    }

    
    @RequestMapping(value = "/createOrUpdate", method = RequestMethod.POST)
    public ModelAndView createOrUpdate(@RequestBody BannerDto bannerDto) {
        
        if (StringUtils.isBlank(bannerDto.getTitle())) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "请填写标题");
        }

        if (StringUtils.isBlank(bannerDto.getBannerUrl())) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "请上传横幅广告图片");
        }
        
        if (StringUtils.isBlank(bannerDto.getBannerDetailUrl())) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "请上传横幅广告详情图片");
        }
        
        if (bannerDto.getBannerOrder() == null) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "请填写横幅广告顺序");
        }
        
        Integer recommendStatus = bannerDto.getRecommendStatus();
        if (recommendStatus != null && recommendStatus.equals(Constant.ENABLE) && StringUtils.isBlank(bannerDto.getRecommendText())) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "被推荐的横幅广告必须要填写推荐按钮文字");
        }

        long currentTime = System.currentTimeMillis();
        Banner banner = BeanUtil.copyProperties(Banner.class, bannerDto);
        banner.setBannerType(Constant.BANNER_TYPE.INDEX);
        banner.setUpdateTime(currentTime);
        banner.setCreateTime(currentTime);

        try {
            
            BannerQueryDto queryDto = new BannerQueryDto();
            if(queryDto.getPage() == null) queryDto.setPage(1);
            queryDto.setRecommendStatus(Constant.ENABLE);
            queryDto.setBannerType(Constant.BANNER_TYPE.INDEX);
            queryDto.setBannerStatus(Constant.ENABLE);
            List<Banner> bannerList = bannerService.getBannerListByCondition(queryDto);
            
            if (banner.getId() == null) {
                if(bannerList.size() > 0 && recommendStatus.equals(Constant.ENABLE)) {
                    return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "操作失败！已经存在一个被推荐的横幅广告！");
                }
                bannerService.save(banner);
            } else {
                if(bannerList.size() > 0 && recommendStatus.equals(Constant.ENABLE) && !banner.getId().equals(bannerList.get(0).getId())) {
                    return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "操作失败！已经存在一个被推荐的横幅广告！");
                }
                bannerService.update(banner);
            }
        } catch (Exception e) {
            logger.error("createOrUpdate failed", e);
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "操作失败");
        }
        return jsonSucess();
    }
    
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ModelAndView delete(@RequestBody BannerDto bannerDto) {
        if (bannerDto.getId() == null) {
            return jsonFailed(ResponseCode.PARAM_ERROR_CAN_NOT_NULL.getCode(), "该横幅广告不存在");
        }
        bannerService.deleteById(bannerDto.getId());
        return jsonSucess();
    }

}
